import os
import smtplib
import time
import unittest
from HTMLTestRunner import HTMLTestRunner
from email.header import Header
from email.mime.text import MIMEText


def send_emall(new_report):
    f = open(new_report, 'rb')
    mail_content = f.read()
    f.close()

    smtpserver = 'smtp.163.com'

    user = 'hu_yy199426767@163.com'
    password = 'qq123123'

    sender = 'hu_yy199426767@163.com'
    receiver = 'huyy@usoftchina.com'

    subject = '测试'

    msg = MIMEText(mail_content, 'html', 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = sender
    msg['To'] = receiver

    smtp = smtplib.SMTP_SSL(smtpserver, 465)
    smtp.helo(smtpserver)
    smtp.ehlo(smtpserver)
    smtp.login(user, password)

    print("发送邮件中。。")

    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()
    print("发送成功！")


def new_report(report_dir):
    lists = os.listdir(report_dir)

    lists.sort(key=lambda fn: os.path.getatime(report_dir + '\\' + fn))
    print(lists)
    print(lists[-1])

    file = os.path.join(report_dir, lists[-1])
    print(file)
    return file


if __name__ == '__main__':
    report_dir = './test_report'
    test_dir = './test_mall'

    discover = unittest.defaultTestLoader.discover(test_dir, pattern='test*.py')
    now = time.strftime("%Y-%m-%d %H_%M_%S")
    report_name = report_dir + '/' + now + 'result.html'

    with open(report_name, 'wb')as f:
        runner = HTMLTestRunner(stream=f, title="测试", description='Test')
        runner.run(discover)
    f.close()

    a = new_report(report_dir)
    send_emall(a)
